package com.cxb;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.amitek.aidl.mqtt.MqttServiceProxy;
import com.amitek.aidl.mqtt.bean.BindStatus;
import com.amitek.aidl.mqtt.bean.BindStatus.UserInfo;
import com.amitek.aidl.mqtt.bean.ConfigStatus;
import com.cxb.entity.EventBusMessage;
import com.cxb.service.CXBMainService;
import com.cxb.utils.Debug;
import com.cxb.utils.SharedPreferencesUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.util.LogUtils;
import de.greenrobot.event.EventBus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.x;

import java.io.UnsupportedEncodingException;

public class WeiXinBindActivity extends BaseActivity {

	private View bt_back;
	private View ll_bind_tip;
	private TextView tv_have_binded;
	private TextView tv_bind_tip;

	private View tv_validate_code_title, rl_qrcode;
	private ImageView iv_qrcode, iv_loading;
	private ProgressDialog progressDialog;
	private HttpUtils httpUtils;
	private TelephonyManager telephonyManager;
	private AlertDialog alertDialog;
	private Handler mHandler;
	private QRCodeUpdateTask qrCodeUpdateTask;
	private int tryCount = 0;
	private static final String TAG = "WeiXinBindActivity";
	private MqttServiceProxy mqttProxy;
	private final static int MAX_TRY_COUNT = 60;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		mqttProxy = CXBMainService.getMqttProxy();
		setContentView(R.layout.activity_weixin);
		tv_validate_code_title = findViewById(R.id.tv_validate_code_title);
		tv_bind_tip = (TextView) findViewById(R.id.bind_weixin_tip);
		iv_qrcode = (ImageView) findViewById(R.id.iv_qrcode);
		iv_loading = (ImageView) this.findViewById(R.id.iv_loading);
		rl_qrcode = this.findViewById(R.id.rl_qrcode);
		rl_qrcode.setVisibility(View.VISIBLE);

		// loadingQrCode();
		iv_qrcode.setClickable(true);
		iv_qrcode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// showLoadingDialog(DIALOG_TYPE_GET_BIND_INFO);
				tryCount = 0;
				loadWXBindInfo();
			}
		});
		mHandler = new Handler();
		new SharedPreferencesUtils(this);

		httpUtils = new HttpUtils();
		httpUtils.configHttpCacheSize(0);
		httpUtils.configDefaultHttpCacheExpiry(0);
		// httpUtils.configRequestRetryCount(5);
		httpUtils.configTimeout(60 * 1000);
		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		init();

	}

	private void loadWXBindInfo() {
		// 1.显示正在获取
		try {
			Log.i("test", "loadWXBindInfo tryCount=" + tryCount
					+ " bindService=" + mqttProxy.bindService()
					+ " configStatus=" + mqttProxy.getConfigStatus());
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		iv_qrcode.setVisibility(View.GONE);
		iv_loading.setVisibility(View.VISIBLE);
		iv_loading.setImageResource(R.drawable.weixin_qr_loading);
		tv_have_binded.setVisibility(View.GONE);
		tv_bind_tip.setVisibility(View.VISIBLE);
		ll_bind_tip.setVisibility(View.VISIBLE);
		startLoadingAninmation();
		try {
			if (!mqttProxy.bindService() || mqttProxy.getConfigStatus() == null) {
				// mqtt未连接成功
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (tryCount > MAX_TRY_COUNT) {
							loadWXInfoError(BindStatusCallBack.ERROR_MQTT_CONNECT_FAIL);
							return;
						}
						tryCount++;
						loadWXBindInfo();

					}
				}, 1000);
				tv_bind_tip.setText(R.string.connecting_mqtt_server);
				return;
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		tv_bind_tip.setText(R.string.getting_weixin_bind_info);

		queryBindStatus(new BindStatusCallBack() {

			@Override
			public void onSuccess(BindStatus bindStatus) {

				boolean bindState = bindStatus.bindStatus;
				if (bindState) {
					ll_bind_tip.setVisibility(View.GONE);
					iv_qrcode.setVisibility(View.GONE);
					tv_have_binded.setVisibility(View.VISIBLE);
					tv_have_binded.setText(getString(R.string.has_bind_weixin,
							bindStatus.weixin.nickName));

					cancelLoadingAninmation();
				} else {
					ll_bind_tip.setVisibility(View.VISIBLE);
					tv_have_binded.setVisibility(View.GONE);
					tv_have_binded.setVisibility(View.GONE);
					tv_bind_tip.setVisibility(View.VISIBLE);
					iv_qrcode.setVisibility(View.GONE);
					tv_bind_tip.setText(R.string.getting_weixin_qrcode);

					new DownLoadQRCodeTask().execute();
				}

			}

			@Override
			public void onFail(final int error) {
				LogUtils.i("onFail error=" + error + " tryCount=" + tryCount);
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (tryCount > MAX_TRY_COUNT) {
							loadWXInfoError(error);
							return;
						}
						tryCount++;
						loadWXBindInfo();

					}
				}, 1000);

			}
		});

		// 2.开始获取
	}

	private void startLoadingAninmation() {
		if (iv_qrcode != null)
			iv_qrcode.setVisibility(View.GONE);

		if (rl_qrcode != null && rl_qrcode.getVisibility() != View.VISIBLE)
			rl_qrcode.setVisibility(View.VISIBLE);
		else if (iv_loading.getAnimation() != null)
			return;

		final RotateAnimation animation = new RotateAnimation(0f, 360f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		animation.getFillAfter();
		LinearInterpolator lin = new LinearInterpolator();
		animation.setInterpolator(lin);
		animation.setDuration(1500l);
		animation.setRepeatCount(100);
		iv_loading.setAnimation(animation);
		animation.start();
	}

	private void cancelLoadingAninmation() {
		if (rl_qrcode == null)
			rl_qrcode = this.findViewById(R.id.rl_qrcode);
		if (iv_loading == null)
			iv_loading = (ImageView) this.findViewById(R.id.iv_loading);
		Animation animation = iv_loading.getAnimation();
		if (animation != null)
			animation.cancel();
		rl_qrcode.setVisibility(View.GONE);

	}

	@Override
	protected void onStart() {
		loadWXBindInfo();
		super.onStart();
	}

	private void init() {

		bt_back = findViewById(R.id.bt_back);
		ll_bind_tip = findViewById(R.id.ll_bind_tip);
		tv_have_binded = (TextView) findViewById(R.id.tv_have_binded);
		bt_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		EventBus.getDefault().register(this);

	}

	public void onEventMainThread(EventBusMessage eventBusMessage) {
		if (eventBusMessage.getEventType() == EventBusMessage.EVENT_TYPE_WEIXIN_BIND_STATE_CHANGE) {
			loadWXBindInfo();
		}
	}

	@Override
	protected void onDestroy() {

		EventBus.getDefault().unregister(this);
		mHandler.removeCallbacks(qrCodeUpdateTask);
		super.onDestroy();
	}

	boolean state;

	@Override
	protected void onStop() {
		try {

			mHandler.removeCallbacks(qrCodeUpdateTask);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onStop();
	}

	@Override
	protected void onResume() {
		tryCount = 0;
		super.onResume();
	}

	class QRCodeUpdateTask implements Runnable {
		public void run() {
			// showLoadingDialog(DIALOG_TYPE_QRCODE_TIME_OUT);
			startLoadingAninmation();

		};
	}

	public class DownLoadQRCodeTask extends AsyncTask<String, Void, Bitmap> {
		int count = 0;

		/**
		 * 表示任务执行之前的操作
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

		}

		/**
		 * 主要是完成耗时的操作
		 */
		@Override
		protected Bitmap doInBackground(String... arg0) {

			HttpClient httpClient = new DefaultHttpClient();

			Bitmap bitmap = null;
			int code = 0;
			HttpResponse httpResponse;
			count = 0;
			while (count++ < 10 && bitmap == null) {
				try {

					String imageUrl = null;
					if (!mqttProxy.isBindService()) {
						continue;
					}
					ConfigStatus configStatus = null;
					try {
						configStatus = mqttProxy.getConfigStatus();
					} catch (RemoteException e2) {
						e2.printStackTrace();
					}
					if (configStatus == null) {
						continue;
					}
					imageUrl = configStatus.wxQrCodeUrl;

					Debug.printfLog("imageUrl=" + imageUrl + "  count=" + count);
					HttpGet httpGet = new HttpGet(imageUrl);
					httpResponse = httpClient.execute(httpGet);
					code = httpResponse.getStatusLine().getStatusCode();
					if (code == 200) {
						HttpEntity httpEntity = httpResponse.getEntity();
						byte[] data = EntityUtils.toByteArray(httpEntity);
						bitmap = BitmapFactory.decodeByteArray(data, 0,
								data.length);
					}

				} catch (Exception e) {
					Log.i("http", "get Weixin Code: " + code);
					e.printStackTrace();
				}

				finally {
					if (httpClient != null
							&& httpClient.getConnectionManager() != null) {
						httpClient.getConnectionManager().shutdown();
					}
				}
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			return bitmap;

		}

		/**
		 * 主要是更新UI的操作
		 */
		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Debug.printfLog(" show image" + result);
			cancelLoadingAninmation();
			iv_qrcode.setVisibility(View.VISIBLE);
			tv_bind_tip.setText(R.string.bind_weixin_tip);
			if (result != null) {
				iv_qrcode.setImageBitmap(result);
			} else {
				loadWXInfoError(BindStatusCallBack.ERROR_NETWORK);

			}

		}
	}

	private void loadWXInfoError(int error) {
		cancelLoadingAninmation();
		iv_qrcode.setImageResource(R.drawable.weixin_retry);
		iv_qrcode.setVisibility(View.VISIBLE);
		tv_bind_tip.setVisibility(View.VISIBLE);
		if (error == BindStatusCallBack.ERROR_NETWORK) {
			tv_bind_tip.setText(R.string.weixin_network_error);
		} else if (error == BindStatusCallBack.ERROR_SERVER_ERROR) {
			tv_bind_tip.setText(R.string.weixin_service_error);
		} else if (error == BindStatusCallBack.ERROR_UNKOWN) {
			tv_bind_tip.setText(R.string.weixin_unkown_error);
		} else if (error == BindStatusCallBack.ERROR_MQTT_CONNECT_FAIL) {
			tv_bind_tip.setText(R.string.connect_server_fail);
		}
	}

	public interface BindStatusCallBack {
		public static final int ERROR_NETWORK = 1;
		public static final int ERROR_UNKOWN = 2;
		public static final int ERROR_SERVER_ERROR = 3;
		public static final int ERROR_URL_IS_NULL = 4;
		public static final int ERROR_MQTT_CONNECT_FAIL = 4;

		void onSuccess(BindStatus bindStatus);

		void onFail(int error);
	}

	public void queryBindStatus(final BindStatusCallBack bindStatusCallBack) {

		if (!mqttProxy.isBindService()) {
			return;
		}
		ConfigStatus configStatus = null;
		try {
			configStatus = mqttProxy.getConfigStatus();
		} catch (RemoteException e2) {
			e2.printStackTrace();
		}
		if (configStatus == null) {
			return;
		}
		String url = configStatus.wxStatusUrl + "";
		// if (TextUtils.isEmpty(url)) {
		// url = "http://wx.ami-tek.com/wsdp/member/load?deviceId=" + url;
		// }
		if (TextUtils.isEmpty(url)) {
			bindStatusCallBack.onFail(BindStatusCallBack.ERROR_URL_IS_NULL);
			return;
		}
		Log.i(TAG, "queryBindStatus url=" + url);

		org.xutils.http.RequestParams requestParams = new org.xutils.http.RequestParams(
				url);
		x.http().get(requestParams, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				try {
					Log.i(TAG,
							"get weixin status result="
									+ new String(result.getBytes("utf-8")));
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (TextUtils.isEmpty(result)) {
					bindStatusCallBack
							.onFail(BindStatusCallBack.ERROR_SERVER_ERROR);
					return;
				}
				try {
					JSONObject jsonObject = new JSONObject(result);
					int status = jsonObject.getInt("status");
					String nickName = null;
					BindStatus bindStatus = new BindStatus();
					bindStatus.bindStatus = status == 1;

					if (status == 1) {
						nickName = jsonObject.getString("nickName");
						bindStatus.weixin = new UserInfo();
						bindStatus.weixin.nickName = nickName;

					}
					bindStatusCallBack.onSuccess(bindStatus);

				} catch (JSONException e) {
					bindStatusCallBack
							.onFail(BindStatusCallBack.ERROR_SERVER_ERROR);
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				bindStatusCallBack.onFail(BindStatusCallBack.ERROR_NETWORK);
				ex.printStackTrace();
			}

			@Override
			public void onCancelled(CancelledException cex) {
			}

			@Override
			public void onFinished() {

			}
		});
	}

}
